package com.devunion.salon.acegi;

import com.devunion.salon.persistence.Login;
import com.devunion.salon.persistence.dao.LoginDao;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Timoshenko Alexander 23.10.2008 : 21:29:53
 */
public class ServiceAuthentication implements UserDetailsService {
    private LoginDao loginDao;

    /**
     * Load user by name.
     *
     * @param username User name.
     * @return Axis user object.
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        if (StringUtils.isBlank(username)) {            
            throw new UsernameNotFoundException("");
        }
        Login login = loginDao.getByLogin(username);
        if (login == null) {            
            throw new UsernameNotFoundException("");
        }

        List<GrantedAuthority> authority = new ArrayList<GrantedAuthority>();
        authority.add(new GrantedAuthorityImpl("ROLE_" + login.getRole().toUpperCase()));

        return new User(login.getLogin(), login.getPassword(), true, true, true, true, authority.toArray(new GrantedAuthority[0]));
    }

    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
}